/**
 * 
 */
package com.kotiln.lgc.lib_network.javahttp;


import android.util.Log;

import org.json.JSONException;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * @author lgc
 *
 */
public abstract class HttpRequest extends BaseHttpRequest

{
private String mPostData;
    
    private String mCharset = "UTF-8";
    
    private String mContentType = "application/json"; //"text/html  x-www-form-urlencoded"  application/json  multipart/form-data;
    
	private LinkedHashMap<String,String> map;
	private HashMap<String, String> headerMap;

	public HttpRequest(String url)
	{
		super(url);
		doInit();
	}

	public HttpRequest(String url,String tradeType)
	{
		super(url, tradeType);
		doInit();
	}
	
	public HttpRequest(String url,String tradeType, String data)
	{
		super(url, tradeType);
		setPostData(data);
		doInit();
	}
	
	public HttpRequest(String url,String tradeType, String post, String charset)
	{
		super(url, tradeType);
		mCharset = charset;
		setPostData(post);
		doInit();
	}
	
	public HttpRequest(String url,String tradeType, String post, String charset, String contentType)
	{
		super(url, tradeType);
		mCharset = charset;
		setPostData(post);
		this.mContentType = contentType;
		doInit();
	}



    //addHeader
	public void addHeader(LinkedHashMap<String,String> map){
		this.map=map;
	};

	//加入自定义header
	public void addCustomHeader(HashMap<String, String> map) { headerMap = map; };
	
	public void setPostData(String post)
	{
		this.mPostData = post;
	}
	
	private void doInit()
	{}
	
	@Override
	protected Result doInBackground(Void...params)
	{
		URL realurl = null;
		InputStream in = null;
		HttpURLConnection conn = null;
		StringBuffer sBuffer = null;
		
		try {
			realurl = new URL(mUrl);
			conn = (HttpURLConnection) realurl.openConnection();
			conn.setDoInput(true); 
			conn.setReadTimeout(20000);
			conn.setConnectTimeout(20000);
			conn.setRequestMethod(mTradeType);
			if (headerMap != null) {
				for (Map.Entry<String, String> entry : headerMap.entrySet()) {
					//System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			if(mTradeType.equalsIgnoreCase("POST"))
			{
//				conn.setRequestProperty("Content-Type", mContentType + ";charset=" + mCharset);
//				conn.setRequestProperty("Accept", mContentType + ";charset=" + mCharset);
				if(map!=null){
					conn.setRequestProperty("account",map.get("account"));
					conn.setRequestProperty("requestTime",map.get("requestTime"));
					conn.setRequestProperty("signature",map.get("signature"));
				}

			    if(mPostData != null)
			    {
			    	BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
			    	byte[] bytes = mPostData.getBytes(mCharset);
			    	out.write(bytes, 0, bytes.length);
			    	out.flush();
			    	out.close();
			    }
			}
			if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK)
			{
				sBuffer = new StringBuffer();
			    byte[] buf = new byte[1024];  
			    in = conn.getInputStream();
			    for (int n; (n = in.read(buf)) != -1;)
			    {  
			        sBuffer.append(new String(buf, 0, n, mCharset));  
			    }  
			}else{
				return new Result(-1, "read error");
			}
			
		} catch (MalformedURLException e) {
			return new Result(-90, "MalformedURLException");
		} catch (ProtocolException e) {
			return new Result(-91, "ProtocolException");
		} catch (UnsupportedEncodingException e) {
			return new Result(-92, "UnsupportedEncodingException");
		} catch(SocketTimeoutException e){
			return new Result(-93, "SocketTimeoutException");
		}catch (UnknownHostException  e) {
			return new Result(-95, "UnknownHostException");
		}catch (IOException e) {
			return new Result(-96, "IOException");
		}
		finally
		{
			try
			{
				if(in != null) in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}  
			if(conn != null) conn.disconnect();
		}
		return new Result(0, sBuffer.toString());
	}
	
	@Override
	protected void onPostExecute(Result result)
	{
//		super.onPostExecute(result);
		try {
			afterTrade(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	protected abstract void afterTrade(Result result) throws JSONException;
}
